import axios from 'axios'
import { ElMessage } from 'element-plus'
import { createUrlParams, isExternal } from '@/utils/index'
import { baseURL } from '@/common'

const request = axios.create({
    // 后端服务的ip地址和端口号
    baseURL,
    timeout: 60000,
    withCredentials: true
})

// 拦截请求
request.interceptors.request.use(
    (config) => {
        const { data = {}, method = 'post', url = '' } = config
        if (
            method.toLowerCase() === 'get' &&
            typeof config.url !== 'undefined'
        ) {
            config.url += createUrlParams(data)
        }
        Object.keys(data).forEach((i) => {
            if (data[i] === null || data[i] === undefined) {
                if (config.dealNull) {
                    data[i] = 0
                } else {
                    data[i] = null
                }
            }
        })
        config.data = data || {}

        // 判断是否是外链
        if (isExternal(url)) {
            config.baseURL = ''
        }
        return config
    },
    (e) => {
        ElMessage.error('请求错误')
        return Promise.reject(e)
    }
)

// 拦截响应
request.interceptors.response.use(
    // 响应成功进入第1个函数，该函数的参数是响应对象
    ({ data: res, config }) => {
        return res
    },
    (e) => {
        console.log('错误响应', e)
        // 处理token失效的问题(续签的问题)
        if (e.code === 'ERR_NETWORK') {
            ElMessage.error('网络错误')
        } else {
            ElMessage.error('请求异常，请稍后重试')
        }

        return Promise.reject(e)
    }
)

export default request
